import React, { Component } from "react";
import {
  Row,
  Col,
  Button,
  Modal,
  Form,
  Input,
  Image,
  Upload,
  message,
  Table,
  Tag,
  Popconfirm,
  Select,
} from "antd";
import { http } from "../../api";
import {
  LoadingOutlined,
  PlusOutlined,
  UploadOutlined,
} from "@ant-design/icons";
import { baseURL } from "../../api/ajax";
import { observer } from "mobx-react";
@observer
export default class Category extends Component {
  state = {
    isModalVisible: false,
    imageUrl: null,
    updateVisible: false,
    columns: [
      {
        title: "序号",
        key: "",
        dataIndex: "",
        render: (v, item, index) => {
          return index;
        },
        align: "center",
      },
      {
        title: "分类图片",
        dataIndex: "logo",
        key: "logo",
        render: (v, item, index) => {
          return (
            v && (
              <Image
                style={{ width: 50, height: 50 }}
                src={v.replace(/public/, baseURL)}
              />
            )
          );
        },
        align: "center",
      },
      {
        title: "分类名称",
        dataIndex: "name",
        key: "name",
        render: (v, item, index) => {
          return v;
        },
        align: "center",
      },
      {
        title: "分类编码",
        dataIndex: "code",
        key: "code",
        render: (v, item, index) => {
          return v;
        },
        align: "center",
      },
      {
        title: "分类详情",
        dataIndex: "details",
        key: "details",
        render: (v, item, index) => {
          return v;
        },
        align: "center",
      },
      {
        title: "操作",
        render: (v, item, index) => {
          return (
            <div>
              <Button
                onClick={() => this.showUpdateModal(item)}
                style={{ marginRight: 10 }}
                type="primary"
                size="small"
              >
                修改
              </Button>
              <Popconfirm
                title="你真的要删除吗?"
                onConfirm={() => this.delconfirm(item)}
                okText="确定"
                cancelText="取消"
              >
                <Button type="danger" size="small">
                  删除
                </Button>
              </Popconfirm>
            </div>
          );
        },
        align: "center",
      },
    ],
    categorylist: [],
  };
  showUpdateModal = (item) => {
    this.setState({
      updateVisible: true,
      item: item,
    });
    setTimeout(() => {
      this.updateform.setFieldsValue(item);
    });
  };
  delconfirm = (item) => {
    // console.log(item);
    http
      .categoryDelete({
        _id: item._id,
      })
      .then((res) => {
        if (res.data.code == 200) {
          var categorylist = this.state.categorylist.filter(
            (val) => val._id !== item._id
          );
          this.setState({
            categorylist: categorylist,
          });
        }
      });
  };
  showModal = (item) => {
    this.setState({
      isModalVisible: true,
      item: item,
    });
  };
  updatehandleOk = () => {
    this.updateform.validateFields().then((value) => {
      http
        .updatecategory({
          ...value,
          _id: this.state.item._id,
        })
        .then((res) => {
          //   console.log(res);
          if (res.data.code == 200) {
            this.setState({
              updateVisible: false,
            });
            this.updateform.resetFields();
            http.categorylist().then((res) => {
              //   console.log(res);
              this.setState({
                categorylist: res.data.val,
              });
            });
          }
        });
    });
  };
  handleOk = () => {
    this.addform.validateFields().then((value) => {
      //   console.log(value);
      http.addcategory(value).then((res) => {
        if (res.data.code == 200) {
          this.setState({
            isModalVisible: false,
          });
          this.addform.resetFields();
          http.categorylist().then((res) => {
            console.log(res);
            this.setState({
              categorylist: res.data.val,
            });
          });
        }
      });
      this.setState({
        isModalVisible: false,
      });
    });
  };
  updatehandleCancel = () => {
    this.setState({
      updateVisible: false,
    });
  };
  handleCancel = () => {
    this.setState({
      isModalVisible: false,
    });
  };

  picupload = () => {
    this.upload.click();
  };
  sendFile = () => {
    var file = this.upload.files[0];
    var datafile = new FormData();
    datafile.append("avatar", file);
    http.sendpic(datafile).then((res) => {
      if (res.data.code == 200) {
        this.setState({
          imageUrl: res.data.path,
        });
        this.addform.setFieldsValue({ logo: res.data.path });
      }
    });
  };
  sendFileupdate = () => {
    var file = this.upload.files[0];
    var datafile = new FormData();
    datafile.append("avatar", file);
    http.sendpic(datafile).then((res) => {
      if (res.data.code == 200) {
        this.setState({
          imageUrl: res.data.path,
        });
        this.updateform.setFieldsValue({ logo: res.data.path });
      }
    });
  };
  componentDidMount() {
    http.categorylist().then((res) => {
      //   console.log(res);
      this.setState({
        categorylist: res.data.val,
      });
    });
  }
  render() {
    const { isModalVisible, imageUrl, categorylist, updateVisible } =
      this.state;
    return (
      <div>
        <h2>分类管理</h2>
        <Row style={{ width: "100%", display: "block" }}>
          <Col>
            <Button
              type="danger"
              style={{ margin: "10px 0" }}
              onClick={this.showModal}
            >
              添加分类
            </Button>
            <Modal
              title="添加分类"
              visible={isModalVisible}
              onOk={this.handleOk}
              onCancel={this.handleCancel}
            >
              <Form layout="vertical" ref={(el) => (this.addform = el)}>
                <Form.Item
                  label="分类名称"
                  name="name"
                  rules={[{ required: true, message: "请输入分类名称" }]}
                >
                  <Input placeholder="请输入分类名称" />
                </Form.Item>
                <Form.Item
                  label="分类编码"
                  name="code"
                  rules={[{ required: true, message: "请输入分类编码" }]}
                >
                  <Input placeholder="请输入分类编码" />
                </Form.Item>
                <Form.Item
                  label="分类描述"
                  name="details"
                  rules={[{ required: true, message: "请输入分类描述" }]}
                >
                  <Input placeholder="请输入分类描述" />
                </Form.Item>
                <Form.Item label="上传图片" name="logo">
                  <input
                    onChange={this.sendFile}
                    type="file"
                    style={{ display: "none" }}
                    ref={(el) => (this.upload = el)}
                  />
                  {imageUrl ? (
                    <div style={{ display: "flex", flexDirection: "column" }}>
                      <Image
                        width={200}
                        style={{ height: 200, borderRadius: 6 }}
                        src={imageUrl.replace(/public/, baseURL)}
                      />
                      <Button
                        style={{ width: 200, marginTop: "10px" }}
                        onClick={this.picupload}
                      >
                        替换图片
                      </Button>
                    </div>
                  ) : (
                    <Button onClick={this.picupload} icon={<UploadOutlined />}>
                      上传图片
                    </Button>
                  )}
                </Form.Item>
              </Form>
            </Modal>
            <Modal
              title="修改分类"
              visible={updateVisible}
              onOk={this.updatehandleOk}
              onCancel={this.updatehandleCancel}
            >
              <Form
                layout="vertical"
                ref={(el) => (this.updateform = el)}
                style={{ width: "100%" }}
              >
                <Form.Item
                  label="分类名称"
                  name="name"
                  rules={[{ required: true, message: "请输入分类名称" }]}
                >
                  <Input placeholder="请输入分类名称" />
                </Form.Item>
                <Form.Item
                  label="分类编码"
                  name="code"
                  rules={[{ required: true, message: "请输入分类编码" }]}
                >
                  <Input placeholder="请输入分类编码" />
                </Form.Item>
                <Form.Item
                  label="分类描述"
                  name="details"
                  rules={[{ required: true, message: "请输入分类描述" }]}
                >
                  <Input placeholder="请输入分类描述" />
                </Form.Item>
                <Form.Item label="上传图片" name="logo">
                  <input
                    onChange={this.sendFileupdate}
                    type="file"
                    style={{ display: "none" }}
                    ref={(el) => (this.upload = el)}
                  />
                  {imageUrl ? (
                    <div style={{ display: "flex", flexDirection: "column" }}>
                      <Image
                        width={200}
                        style={{ height: 200, borderRadius: 6 }}
                        src={imageUrl.replace(/public/, baseURL)}
                      />
                      <Button
                        style={{ width: 200, marginTop: "10px" }}
                        onClick={this.picupload}
                      >
                        替换图片
                      </Button>
                    </div>
                  ) : (
                    <Button onClick={this.picupload} icon={<UploadOutlined />}>
                      上传图片
                    </Button>
                  )}
                </Form.Item>
              </Form>
            </Modal>

            <Table
              columns={this.state.columns}
              dataSource={categorylist}
              style={{ marginTop: 10, width: "100%" }}
              bordered
              size="small"
              id="mytable"
              rowKey={(item) => item._id}
              pagination={{ pageSize: 5 }}
            />
          </Col>
        </Row>
      </div>
    );
  }
}
